﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace SocketPostData.BLL
{
    /// <summary>
    /// 缓存辅助类
    /// </summary>
    public static class CacheHelper
    {

        /// <summary>
        /// 获取数据缓存
        /// </summary>
        /// <param name="CacheKey">键</param>
        public static object GetCache(string CacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            return objCache[CacheKey];
        }
        
        /// <summary>
        /// 获取数据缓存
        /// </summary>
        /// <param name="CacheKey">键</param>
        public static List<T> GetCache<T>(string CacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            if(objCache[CacheKey] == null)
            {
                return null;
            }
            else
            {
                return objCache[CacheKey] as List<T>;
            }
        }

        /// <summary>
        /// 设置数据缓存
        /// </summary>
        public static void SetCache(string CacheKey, object objObject)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject);
        }

        /// <summary>
        /// 设置数据缓存
        /// </summary>
        public static void SetCache(string CacheKey, object objObject, TimeSpan Timeout)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            try
            {
                objCache.Insert(CacheKey, objObject, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);
            }
            catch (Exception ex)
            {
                objCache.Insert(CacheKey, objObject, null, DateTime.Now.AddYears(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
            }
        }

        /// <summary>
        /// 移除全部缓存
        /// </summary>
        public static bool RemoveAllCache()
        {
            try
            {
                System.Web.Caching.Cache _cache = HttpRuntime.Cache;
                IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
                while (CacheEnum.MoveNext())
                {
                    _cache.Remove(CacheEnum.Key.ToString());
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

    }
}
